package api

import (
	"client/common"
	"client/global"
	"errors"
	"github.com/gin-gonic/gin"
	"strings"
)

func UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  errors.New("文件接收失败"),
		})
		return
	}
	if file.Size > 1024*1024*4 {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  errors.New("文件过大"),
		})
		return
	}
	imgType := []string{"png", "jpg", "gif", "PNG", "JPG", "GIF"}
	str := strings.Split(file.Filename, ".")
	fileName := str[1]
	if !strings.Contains(strings.Join(imgType, ","), fileName) {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  errors.New("文件格式有误"),
		})
		return
	}
	//todo: 生成唯一名称
	id := global.UUidInit()
	f := id + fileName
	//todo: 上传阿里云
	url := common.AliUploadFile(f, file)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"url":  url,
	})
	return
}
